package com.lzx.iteam;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceCountAdapter;
import com.lzx.iteam.adapter.AttendanceCountMonthAdapter;
import com.lzx.iteam.bean.AttendanceCountData;
import com.lzx.iteam.bean.DateData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetAttendanceCountMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.PreferenceUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by Megan on 16/4/8.
 */
public class AttendanceCountActivity extends Activity implements View.OnClickListener {

    private ImageView mIvArrow;
    private TextView mTvTitle,mTvRule;
    private LinearLayout mLlBack, mLlTitle;
    private RelativeLayout mRlGuide;
    private ListView mLvList;
    private AttendanceCountAdapter mAdapter;
    private ArrayList<AttendanceCountData> attendanceCountDatas = new ArrayList<AttendanceCountData>();
    private String mAttendanceFormId;
    private String mGroupId;
    private final int GET_COUNT_LIST = 1001;
    private Dialog mDialog;
    private int mMonth;
    private int mYear;
    private ArrayList<DateData> dateDatas = new ArrayList<DateData>();
    private PreferenceUtil mPreferenceUtil;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case GET_COUNT_LIST:
                    if (msg.arg1 == 0) {
                        attendanceCountDatas.clear();
                        attendanceCountDatas.addAll((ArrayList<AttendanceCountData>) msg.obj);
                        mAdapter.bindData(attendanceCountDatas);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(AttendanceCountActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(AttendanceCountActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.attendance_count_layout);
        initViews();
        getAttendanceCountMsg();
    }

    private void initViews() {
        mIvArrow = (ImageView) findViewById(R.id.iv_attendance_count_arrow);
        mTvTitle = (TextView) findViewById(R.id.tv_attendance_count_title);
        mTvRule = (TextView) findViewById(R.id.tv_attendance_count_rule);
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_count_back);
        mLlTitle = (LinearLayout) findViewById(R.id.ll_attendance_count_title);
        mLvList = (ListView) findViewById(R.id.lv_attendance_count_list);
        mRlGuide = (RelativeLayout) findViewById(R.id.rl_attendance_count_guide);
        mLlBack.setOnClickListener(this);
        mLlTitle.setOnClickListener(this);
        mTvRule.setOnClickListener(this);
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mAttendanceFormId = intent.getStringExtra("form_id");
        mAdapter = new AttendanceCountAdapter(this, mGroupId, mAttendanceFormId);
        mLvList.setAdapter(mAdapter);
        Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1

        mTvTitle.setText("考勤统计(" + mMonth + "月)");
        int temp_month = mMonth;
        int temp_year=mYear;
        DateData dateData = new DateData();
        dateData.setMonth(temp_month);
        dateData.setYear(temp_year);
        dateDatas.add(dateData);
        for (int i = 0; i < 3; i++) {
            DateData dateData1 = new DateData();
            if (temp_month == 1) {
                temp_month=12;
                temp_year=temp_year-1;
                dateData1.setMonth(temp_month);
                dateData1.setYear(temp_year);
            }else{
                temp_month=temp_month-1;
                dateData1.setMonth(temp_month);
                dateData1.setYear(temp_year);
            }
            dateDatas.add(dateData1);
        }

        mPreferenceUtil = PreferenceUtil.getInstance(this);

        boolean isFrist = mPreferenceUtil.getBoolean("attendance_coun_member_frist",true);
        if (isFrist){
            mRlGuide.setVisibility(View.VISIBLE);
            mPreferenceUtil.save("attendance_coun_member_frist",false);
        }else{
            mRlGuide.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_count_back:
                finish();
                break;
            case R.id.tv_attendance_count_rule:
//                Intent intent=new Intent(AttendanceCountActivity.this,HorHelpActivity.class);
                Intent intent=new Intent(AttendanceCountActivity.this,SalaryMainActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_attendance_count_title:
                if (dateDatas != null) {
                    if (mIvArrow.getDrawable().getCurrent().getConstantState()
                            .equals(getResources().getDrawable(R.drawable.arrow_up).getConstantState())) {
                        mIvArrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        mIvArrow.setImageResource(R.drawable.arrow_up);
                        if (dateDatas != null && dateDatas.size() > 0) {
                            showMonthDialog();
                        }
                    }
                }

                break;
        }
    }

    private void getAttendanceCountMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, mAttendanceFormId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MONTH, mYear + "_" + mMonth));
        GetAttendanceCountMsg msg = new GetAttendanceCountMsg(mHandler.obtainMessage(GET_COUNT_LIST));
        msg.mParams = nvps;
        msg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_ANALYSIS;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }


    /**
     */
    private void showMonthDialog() {

        mDialog = new AlertDialog.Builder(this)
                .create();
        mDialog.show();
        Window window = mDialog.getWindow();
        WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f;   // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.attendance_team_pop_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        ListView listView = (ListView) window.findViewById(R.id.lv_attendance_team_list);
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);


        AttendanceCountMonthAdapter adapter = new AttendanceCountMonthAdapter(AttendanceCountActivity.this);
        adapter.bindData(dateDatas);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mMonth = dateDatas.get(i).getMonth();
                mYear = dateDatas.get(i).getYear();
                getAttendanceCountMsg();
                mTvTitle.setText("考勤统计("+mMonth+")月");
                mDialog.dismiss();
            }
        });

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mIvArrow.setImageResource(R.drawable.arrow_down);
            }
        });

    }

    /**
     * 跳转到考勤日历页面
     * @param attendanceCountData
     */
    public void toAttendanceCalendarActivity(AttendanceCountData attendanceCountData){
        Intent intent = new Intent(this, AttendanceCalendarActivity.class);
        intent.putExtra("userId", attendanceCountData.getUserId());
        intent.putExtra("userName", attendanceCountData.getUserName());
        intent.putExtra("group_id", mGroupId);
        intent.putExtra("form_id", mAttendanceFormId);
        intent.putExtra("year",mYear);
        intent.putExtra("month",mMonth);
        startActivity(intent);
    }

    public void setGuideGone(){
        if (mRlGuide.getVisibility() == View.VISIBLE){
            mRlGuide.setVisibility(View.GONE);
        }
    }


}
